import os
import cv2
import numpy as np
import pyautogui
import time
import platform
from datetime import datetime
import mss

class YijiAutoClicker:
    def __init__(self):
        pyautogui.FAILSAFE = True
        pyautogui.PAUSE = 0.1
        
        # 初始化mss截图器
        self.sct = mss.mss()
        
        # 图片缓存
        self.image_cache = {}
        
        # 修复macOS高分屏坐标偏移
        self.scale_factor = 2 if self.fast_screenshot().shape[1] > pyautogui.size()[0] else 1
        
        # 检测当前系统
        self.system = platform.system()
        self.log(f"检测到系统: {self.system}")
        
        # 获取当前脚本所在目录
        current_dir = os.path.dirname(os.path.abspath(__file__))
        yiji_dir = os.path.join(current_dir, 'yiji')
        
        # 重新组织的按钮配置，支持子目录
        self.button_groups = {
            "初始界面": self._filter_system_files([
                "初始界面.png"
            ], yiji_dir),
            "观看广告": self._filter_system_files([
                "0.观看广告-mac.png",
                "0.任意位置关闭-mac.png",
                "0.观看广告.png"
            ], yiji_dir),
            "前往遗迹": self._filter_system_files([
                "1.前往遗迹按钮-mac.png",
                "1.前往遗迹按钮.png"
            ], yiji_dir),
            "开始挑战": self._filter_system_files([
                "2.开始挑战按钮-mac.png",
                "2.开始挑战按钮.png"
            ], yiji_dir),
            "点击挑战": self._filter_system_files([
                "5.点击挑战按钮-mac.png",
                "5.点击挑战按钮.png"
            ], yiji_dir),
            "选择队长": self._filter_system_files([
                "6.选择队长按钮-mac.png",
                "6.选择队长按钮.png"
            ], yiji_dir),
            "选择英雄装备": self._filter_system_files([
                "7.选择英雄或者装备/7.1up2-mac.png",
                "7.选择英雄或者装备/7.2up3-mac.png",
                "7.选择英雄或者装备/7.3up4-mac.png",
                "7.选择英雄或者装备/7.4up5-mac.png",
                "7.选择英雄或者装备/7.juexing-mac.png",
                "7.选择英雄或者装备/7.选择装备-mac.png",
                "7.选择英雄或者装备/7.1up2.png",
                "7.选择英雄或者装备/7.2up3.png",
                "7.选择英雄或者装备/7.3up4.png",
                "7.选择英雄或者装备/7.4up5.png",
                "7.选择英雄或者装备/7.juexing.png",
                "7.选择英雄或者装备/7.选择装备.png"
            ], yiji_dir),
            "确定": self._filter_system_files([
                "8.一次挑战结束后的确定按钮-mac.png",
                "8.一次挑战结束后的确定按钮.png"
            ], yiji_dir),
            "进入下一层": self._filter_system_files([
                "9.进去下一层2.0/9.下一层箭头-mac.png",
                "12.进入下一层-mac.png",
                "9.进去下一层2.0/9.下一层箭头.png",
                "12.进入下一层.png"
            ], yiji_dir),
            "普通事件": self._filter_system_files([
                "10.普通事件-mac.png",
                "10.普通事件.png"
            ], yiji_dir),
            "选择神器": self._filter_system_files([
                "11.神器/11.紫色-mac.png",
                "11.神器/11.黄色-mac.png",
                "11.神器/11.丢弃-mac.png",
                "11.神器/11.紫色.png",
                "11.神器/11.黄色.png",
                "11.神器/11.丢弃.png"
            ], yiji_dir),
            "退出商店": self._filter_system_files([
                "13.退出商店-mac.png",
                "13.退出商店.png",
            ], yiji_dir),
            "挑战结束": self._filter_system_files([
                "14.挑战结束.png"
            ], yiji_dir)
        }
        
    def log(self, message):
        """打印带时间戳的日志"""
        print(f"[{datetime.now().strftime('%H:%M:%S')}] {message}")
    
    def _filter_system_files(self, file_list, base_dir):
        """根据系统过滤图片文件"""
        filtered_files = []
        
        for filepath in file_list:
            full_path = os.path.join(base_dir, filepath)
            
            # 检查文件是否存在
            if not os.path.exists(full_path):
                continue
            print(self.system)
            # 根据系统过滤
            if self.system == "Darwin":  # macOS
                # macOS优先使用-mac结尾的图片
                if filepath.endswith("-mac.png"):
                    filtered_files.append(full_path)
            elif self.system == "Windows":  # Windows
                # Windows忽略-mac结尾的图片
                if not filepath.endswith("-mac.png"):
                    filtered_files.append(full_path)
            else:  # Linux或其他系统
                # 其他系统使用通用图片
                if not filepath.endswith("-mac.png"):
                    filtered_files.append(full_path)
        
        # 打印过滤结果
        self.log(f"{os.path.basename(base_dir)}目录 - {self.system}系统过滤后图片: {[os.path.basename(f) for f in filtered_files]}")
        return filtered_files
    
    def load_image(self, filepath):
        """安全加载图片，带缓存"""
        if filepath in self.image_cache:
            return self.image_cache[filepath]
            
        try:
            data = np.fromfile(filepath, dtype=np.uint8)
            img = cv2.imdecode(data, cv2.IMREAD_COLOR)
            if img is not None:
                self.image_cache[filepath] = img
            return img
        except Exception as e:
            self.log(f"加载图片失败 {filepath}: {e}")
            return None
    
    def click_center_screen(self):
        """点击屏幕中心（用于7号按钮的随便点）"""
        screen_width, screen_height = pyautogui.size()
        center_x = screen_width // 2
        center_y = screen_height // 2
        
        try:
            # 修复macOS高分屏坐标偏移
            fixed_pos = (int(center_x / self.scale_factor), int(center_y / self.scale_factor))
            pyautogui.click(fixed_pos)
            self.log(f"点击屏幕中心: {fixed_pos} (原始坐标: ({center_x}, {center_y}), 缩放因子: {self.scale_factor})")
            return True
        except pyautogui.FailSafeException:
            self.log("紧急停止！鼠标移到左上角")
            return False

    def fast_screenshot(self):
        """使用mss进行快速截图"""
        try:
            img = self.sct.grab(self.sct.monitors[0])
            return np.array(img)[:, :, :3]  # 去掉alpha通道
        except Exception as e:
            self.log(f"mss截图失败，使用pyautogui: {e}")
            screenshot = pyautogui.screenshot()
            return cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)
    

    def find_all_buttons_group(self, group_name, file_list, confidence=0.7):
        """查找一组图片的所有匹配位置，返回位置和置信度（每个模板只保留最高置信度的一个）"""
        all_buttons = []
        
        start_time = time.time()
        self.log(f"开始查找按钮组，共{len(file_list)}个图片")
        
        screenshot_start = time.time()
        screenshot = self.fast_screenshot()
        screenshot_time = (time.time() - screenshot_start) * 1000
        self.log(f"截图耗时: {screenshot_time:.1f}ms")
        
        for filepath in file_list:
            if not os.path.exists(filepath):
                continue
            template = self.load_image(filepath)
            if template is None:
                continue
            try:
                result = cv2.matchTemplate(screenshot, template, cv2.TM_CCOEFF_NORMED)
                _, max_val, _, max_loc = cv2.minMaxLoc(result)
                
                if max_val >= confidence:
                    h, w = template.shape[:2]
                    
                    # 水平中心，垂直中心往下1/2高度
                    click_x = max_loc[0] + w//2
                    # 特殊处理：下一层箭头往下移3个1/2高度
                    if filepath.endswith("下一层箭头.png") or filepath.endswith("下一层箭头-mac.png"):
                        click_y = max_loc[1] + h//2 + h//2 + h//2
                    elif filepath.endswith("退出商店-mac.png") or filepath.endswith("退出商店.png"):
                        click_x = max_loc[0] + w - w//4  # 往右移到x按钮位置
                        click_y = max_loc[1] + h//4  # 往上移到x按钮位置
                    else:
                        click_y = max_loc[1] + h//2 # 正常往下移1/2高度
                    
                    all_buttons.append(((click_x, click_y), max_val, filepath))
                    self.log(f"找到按钮 {os.path.basename(filepath)}: {click_x}, {click_y} (置信度: {max_val:.2f})")
            except Exception as e:
                self.log(f"查找按钮失败 {filepath}: {e}")
        
        total_time = (time.time() - start_time) * 1000
        self.log(f"按钮组查找完成， group：{group_name}，耗时: {total_time:.1f}ms，找到{len(all_buttons)}个按钮")
        return all_buttons
    
    def click_fixed_coordinate(self, x, y, times=1):
        """点击固定坐标多次"""
        # 修复macOS高分屏坐标偏移
        fixed_pos = (int(x / self.scale_factor), int(y / self.scale_factor))
        
        self.log(f"开始点击固定坐标: {fixed_pos}, 次数: {times}")
        
        for i in range(times):
            try:
                pyautogui.click(fixed_pos)
                self.log(f"第{i+1}次点击固定坐标: {fixed_pos}")
                time.sleep(0.1)
            except pyautogui.FailSafeException:
                self.log("紧急停止！鼠标移到左上角")
                return False
        return True
        
    def run_auto_mode(self):
        """全点击模式：找到所有匹配的按钮全部点击"""
        print("=== 遗迹活动自动点击器 ===")
        print("鼠标移到左上角停止，Ctrl+C退出")
        print("3秒后开始...")
        
        time.sleep(3)
        
        try:
            while True:
                # 首先检测是否在初始界面
                init_interface_files = self.button_groups.get("初始界面", [])
                if init_interface_files:
                    init_button_data = self.find_all_buttons_group("初始界面", init_interface_files, 0.65)
                    if init_button_data:
                        # 获取屏幕尺寸
                        screen_width, screen_height = pyautogui.size()
                        # 计算屏幕垂直正中间，水平1/4的位置
                        center_x = screen_width // 4  # 水平1/4处
                        center_y = screen_height // 2  # 垂直正中间
                        
                        self.log(f"检测到初始界面，开始点击屏幕垂直正中间，水平1/4处({center_x}, {center_y}) 15次")
                        # 点击固定坐标15次
                        if not self.click_fixed_coordinate(center_x, center_y, 15):
                            return
                
                # 扫描所有按钮组
                for group_name, file_list in self.button_groups.items():
                    # 跳过初始界面检测，因为已经在上面检测过了
                    if group_name == "初始界面":
                        continue
                        
                    button_data = self.find_all_buttons_group(group_name, file_list, 0.60)
                    
                    if button_data:
                        self.log(f"检测到 {len(button_data)} 个{group_name}按钮")
                        for pos, conf, filepath in button_data:
                            try:
                                # 修复macOS高分屏坐标偏移
                                fixed_pos = (int(pos[0] / self.scale_factor), int(pos[1] / self.scale_factor))
                                pyautogui.click(fixed_pos)
                                self.log(f"点击 {group_name}: {fixed_pos} (原始坐标: {pos}, 缩放因子: {self.scale_factor}) [{os.path.basename(filepath)}]")
                                time.sleep(0.1)
                            except pyautogui.FailSafeException:
                                self.log("紧急停止！鼠标移到左上角")
                                return False
                    else:
                        self.log(f"未检测到 {group_name} 按钮")
                    
        except KeyboardInterrupt:
            self.log("\n程序退出")

if __name__ == "__main__":
    clicker = YijiAutoClicker()
    clicker.run_auto_mode()